import axios from 'axios'
import Cookies from 'js-cookie'
// 创建一个 axios 实例
const service = axios.create({
  baseURL: 'http://10.198.48.190:80',
  timeout: 10000,
})

//axios.defaults.baseURL = 'http://localhost:8080/api'

// 添加请求拦截器
service.interceptors.request.use(
  function (req) {
    if (req.url !== '/login') {
      //给请求头的设置Token, Cookies.get()用于获取存放在 Cookie 的 Token
      req.headers['authorization'] = Cookies.get('authorization')
    }
    return req
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
service.interceptors.response.use(
  function (response) {
    const result = response.data
    if (result.code === 401) {
      Cookies.remove('authorization')
      Cookies.remove('userId')
      Cookies.remove('mail')
      Cookies.remove('avatar')
      Cookies.remove('nickName')
      return Promise.reject(result)
    }

    if (result.code === 500) {
      result.message = '服务器出错'
      return Promise.reject(result)
    }

    if (result.code !== 200) {
      return Promise.reject(result)
    }
    return result
  },

  function (error) {
    return Promise.reject(error)
  }
)

export default service
